import React, { ReactElement, useState, useEffect } from 'react';
import { getServiceType } from '@/api/service-type';
import {
  Button,
  Tag,
  Space,
  Menu,
  Table,
  Dropdown,
  DatePicker,
  Popconfirm,
  message,
  Tree,
} from 'antd';

import ProForm, {
  DrawerForm,
  ProFormText,
  ProFormDateRangePicker,
  ProFormSelect,
  ProFormTextArea,
} from '@ant-design/pro-form';
interface Props {
  reload: () => void;
}

import { addServiceType } from '@/api/service-type';
export default function AddServe({ reload }: Props): ReactElement {
  //树形控件点击保存所选项
  const [checkedKeys, setCheckedKeys] = useState<any>({ checked: ['0'] });

  const onCheck = (checkedKeysValue: any) => {
    setCheckedKeys(checkedKeysValue);
    // console.log(checkedKeysValue);
  };

  //获取树形空间所需求的数据
  useEffect(() => {
    getServeType();
  }, []);

  const [treeData, setTreeData] = useState<any[]>([]);
  const getServeType = async () => {
    const res = await getServiceType({});
    // console.log(res, 'res');

    if (res.status == 200) {
      // console.log(res.data.rows.children, 'menu');
      setTreeData([...res.data.rows.children]);
    }
  };
  return (
    <DrawerForm
      title="新建表单"
      trigger={<Button style={{ marginRight: '20px' }}>新增部门</Button>}
      width={500}
      drawerProps={{
        forceRender: true,
        destroyOnClose: true,
      }}
      onFinish={async (values) => {
        console.log(checkedKeys.checked, 'values');
        if (checkedKeys.checked.length == 1) {
          let data = {
            name: values.name,
            Pid: checkedKeys.checked[0],
          };
          const res = await addServiceType(data);
          // console.log(res, 'dres');
          if (res.status == 200) {
            message.success('新增部门成功');
            setCheckedKeys({ checked: ['0'] });
            reload();
            return true;
          }
        } else if (checkedKeys.checked.length > 2) {
          message.error('只能选择一个上级部门');
        } else {
          let data = {
            name: values.name,
            Pid: checkedKeys.checked[1].toString(),
          };
          const res = await addServiceType(data);
          // console.log(res, 'data');
          if (res.status == 200) {
            message.success('新增部门成功');
            setCheckedKeys({ checked: ['0'] });
            reload();
            return true;
          }
        }
      }}
    >
      <ProFormText label="部门名称：" placeholder="" name="name" />

      <ProFormSelect label="权限选择">
        <Tree
          checkable
          // onExpand={onExpand}
          // expandedKeys={expandedKeys}
          autoExpandParent={true}
          onCheck={onCheck}
          checkedKeys={checkedKeys}
          checkStrictly
          // onSelect={onSelect}
          // selectedKeys={selectedKeys}
          treeData={treeData}
        />
      </ProFormSelect>
    </DrawerForm>
  );
}
